/* eslint-disable no-const-assign,prefer-destructuring */
/**
 * Created by mar105 on 2019-01-04.
 */

import React, { Component } from 'react';
import { Modal, Layout, Form, Spin, Tabs, Avatar, Select, message } from 'antd';
import CommonSales from '../../Common/CommonBillEvent'; /* 继承销售模块业务功能 */
import * as commonFunc from '../../Common/commonFunc'; /* 通用单据方法 */ /* 通用单据方法 */
import Toolbar from '../../Common/ToolBar/ToolBarNew';
import StaticEditTable from '../../Common/CommonTable'; /* 可编辑表格 */
import styles from '../../../index.less';
import CommonView from '../../Common/CommonView';
import SplitPaste from './SplitPaste';
import CommonBase from '../../Common/CommonBase'; /* 获取配置及数据 */
import * as commonUtils from '../../../utils/utils'; /* 通用方法 */
import * as commonBusiness from '../../Common/commonBusiness'; /* 单据业务功能 */
import * as commonConfig from '../../../utils/config';
import * as commonServices from '../../../services/services'; /*   服务类   */


const { Header, Content } = Layout;
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;


class WorkOrder extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    // this.props.onSaveState({
    //   checkProcessClassifyData: [], /* 选择工序分类数据 */
    //   sBackProcessData: [], /* 后道工艺数据 */
    //   controlConfig: {}, /* 控制表表配置 */
    //   controlColumn: [], /* 显示的控制表表头 */
    //   controlShowConfig: [], /* 控制表显示配置 */
    //   controlData: [], /* 控制表数据 */
    //   controlDelData: [], /* 控制表数据 */
    //   controlSelectedRowKeys: [], /* 控制表数据 */
    //
    //   materialsConfig: {}, /* 材料表表配置 */
    //   materialsColumn: [], /* 显示的材料表表头 */
    //   materialsShowConfig: [], /* 材料表显示配置 */
    //   materialsData: [], /* 材料表数据 */
    //   materialsDelData: [], /* 材料表数据 */
    //   materialsSelectedRowKeys: [], /* 材料表数据 */
    //
    //   processConfig: {}, /* 工序表表配置 */
    //   processColumn: [], /* 显示的工序表表头 */
    //   processShowConfig: [], /* 工序表显示配置 */
    //   processData: [], /* 工序表数据 */
    //   processDelData: [], /* 工序表数据 */
    //   processSelectedRowKeys: [], /* 材料表数据 */
    // });
  }

  componentWillReceiveProps(nextProps) {
    let {
      controlColumn, materialsColumn, processColumn,
    } = nextProps;
    const { formData, currentId } = nextProps;
    if (commonUtils.isEmptyArr(controlColumn) && formData.length > 0) {
      const controlConfig = formData.filter(item => item.sTbName.toUpperCase() === 'MftWorkOrderControl'.toUpperCase())[0];
      controlColumn = commonFunc.getHeaderConfig(controlConfig, controlColumn);

      const materialsConfig = formData.filter(item => item.sTbName.toUpperCase() === 'MftWorkOrderMaterials'.toUpperCase())[0];
      materialsColumn = commonFunc.getHeaderConfig(materialsConfig, materialsColumn);

      const processConfig = formData.filter(item => item.sTbName.toUpperCase() === 'MftWorkOrderProcess'.toUpperCase())[0];
      processColumn = commonFunc.getHeaderConfig(processConfig, processColumn);

      this.handleGetData(controlConfig, materialsConfig, processConfig);

      this.props.onSaveState({
        controlConfig, controlColumn, materialsConfig, materialsColumn, processConfig, processColumn,
      });
    }

    // 未清复制到时，产品ID需要再获取动态部件
    const sId = currentId !== undefined ? currentId : '';
    if (sId === '' && commonUtils.isNotEmptyObject(this.props.masterData) && !this.props.bGetPartsData) {
      const { sAllPartsName } = this.props.masterData;
      if (sAllPartsName !== undefined) {
        const allPartsName = sAllPartsName.split(',');
        const sPartsName = allPartsName[0];
        if (commonUtils.isEmptyObject(this.props.masterConfig[`dSumPQty${sPartsName}`])) {
          this.handleMasterChange('master', 'sProductId');
          this.props.onSaveState({ bGetPartsData: true });
        }
      }
    }
  }

  shouldComponentUpdate(nextProps) {
    const { controlColumn, slaveConfig } = nextProps;
    return Object.keys(slaveConfig).length > 0 && commonUtils.isNotEmptyArr(controlColumn);
  }

  getMenuStatus = (menu) => {
    if (menu.sControlName === 'BtnCalculation') {
      return !this.props.enabled;
    }
  };

  /* 获取表数据 */
  handleGetData = (controlConfig, materialsConfig, processConfig) => {
    const { currentId } = this.props; /* 当前页签数据 */
    const sId = currentId !== undefined ? currentId : ''; /* 数据Id */
    this.props.handleGetDataSet({
      name: 'control', configData: controlConfig, condition: { sSqlCondition: { sParentId: sId } },
    });
    this.props.handleGetDataSet({
      name: 'materials', configData: materialsConfig, condition: { sSqlCondition: { sParentId: sId } },
    });
    this.props.handleGetDataSet({
      name: 'process', configData: processConfig, condition: { sSqlCondition: { sParentId: sId } },
    });
    this.props.onSaveState({ pageLoading: false });
  };

  handleBackProcessData = async () => {
    const { token } = this.props.app;
    const { sModelsId, masterConfig, sBackProcessData } = this.props;
    if (sBackProcessData === undefined || sBackProcessData === '') {
      const sBackProcess = masterConfig.gdsconfigformslave.filter(item => item.sName === 'sBackProcess')[0];
      const url = `${commonConfig.server_host}business/getSelectDataBysControlId/${sBackProcess.sId}?sModelsId=${sModelsId}`;
      const values = { sKeyUpFilterName: '', sSqlCondition: {} };

      const masterReturn = (await commonServices.postValueService(token, values, url)).data;
      if (masterReturn.code === 1) {
        const sBackProcessDataValue = masterReturn.dataset.rows;
        this.props.onSaveState({ sBackProcessData: sBackProcessDataValue });
      } else {
        message.warn(masterReturn.msg);
      }
    }
  }

  handleForm = (form) => {
    this.form = form;
  };

  /* 非列表联动下拉 */
  handleMasterChange = async (name, sFieldName, changeValue, sId, dropDownData) => {
    /* 数据集类型，对象型为Map 数组型为List */
    const {
      masterData, masterConfig, sModelsId, app,
    } = this.props;
    const { token } = app;
    let { sBackProcessClassifyData } = this.props;

    let { sAllPartsName } = masterData;
    if (sFieldName === 'sProductId') {
      await this.handleBackProcessData();
      let allPartsName = [];
      if (sAllPartsName !== undefined) {
        allPartsName = sAllPartsName.split(',');
      }

      if (allPartsName.length > 0 && masterConfig.gdsconfigformslave.filter(item => item.sName === `sMaterialsName${allPartsName[0]}`).length > 0 &&
        (sBackProcessClassifyData !== undefined && sBackProcessClassifyData !== '' && sBackProcessClassifyData.length > 0 &&
        masterConfig.gdsconfigformslave.filter(item => item.sName === `${sBackProcessClassifyData[0].sId}${allPartsName[0]}`).length > 0)) {
        let iIndex;
        allPartsName.forEach((sPartsName) => {
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `dSumPQty${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `sMaterialsName${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `iPrintModePo${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `iPositiveColor${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }

          if (sBackProcessClassifyData !== '') {
            sBackProcessClassifyData.filter(processClassify => processClassify.sType !== '3').forEach((processClassify) => {
              iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === processClassify.sId + sPartsName);
              if (iIndex > -1) {
                masterConfig.gdsconfigformslave.splice(iIndex, 1);
              }
            });
          }
        });
        if (sBackProcessClassifyData !== '') {
          sBackProcessClassifyData.filter(processClassify => processClassify.sType === '3').forEach((processClassify) => {
            iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === processClassify.sId);
            if (iIndex > -1) {
              masterConfig.gdsconfigformslave.splice(iIndex, 1);
            }
          });
        }
      }


      let sProductClassifyId;
      if (changeValue !== null && changeValue !== undefined) {
        sProductClassifyId = changeValue.sProductClassifyId;
        sAllPartsName = changeValue.sAllPartsName;
      } else {
        sProductClassifyId = masterData.sProductClassifyId;
      }
      if (commonUtils.isEmpty(sProductClassifyId)) {
        return;
      }
      const sBackProcessClassify = masterConfig.gdsconfigformslave.filter(item => (item.sName.toLowerCase() === 'sbackprocessclassify'))[0];

      const values = { sKeyUpFilterName: '', sSqlCondition: { sProductClassifyId } };
      const dataReturn = (await commonServices.postValueService(token, values, `${commonConfig.server_host}business/getSelectDataBysControlId/${sBackProcessClassify.sId}?sModelsId=${sModelsId}`)).data;
      /*   接收返回值   */
      /*   成功的话刷新页面(同步主表和从表数据),不成功就弹出错误提示   */
      if (dataReturn.code === 1) { /*   成功   */
        const { rows } = dataReturn.dataset;

        allPartsName = [];
        if (sAllPartsName !== undefined) {
          allPartsName = sAllPartsName.split(',');
        }

        sBackProcessClassifyData = rows;
        if (allPartsName.length > 0 && masterConfig.gdsconfigformslave.filter(item => item.sName === `sMaterialsName${allPartsName[0]}`).length <= 0 &&
          sBackProcessClassifyData !== undefined && sBackProcessClassifyData !== '' && sBackProcessClassifyData.length > 0 &&
          masterConfig.gdsconfigformslave.filter(item => item.sName === `${sBackProcessClassifyData[0].sId}${allPartsName[0]}`).length <= 0) {
          const sumPQtyConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'dSumPQty').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'dSumPQty')[0] : [];
          const materialsNameConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'sMaterialsName').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'sMaterialsName')[0] : [];
          const printModePoConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'iPrintModePo').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'iPrintModePo')[0] : [];
          const positiveColorConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'iPositiveColor').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'iPositiveColor')[0] : [];
          const processNameConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === 'sProcessName').length > 0 ? masterConfig.gdsconfigformslave.filter(item => item.sName === 'sProcessName')[0] : [];

          let ConfigNew;
          allPartsName.forEach((item) => {
            ConfigNew = { ...sumPQtyConfig };
            ConfigNew.sName = `dSumPQty${item}`;
            ConfigNew.sAssignField = ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);

            ConfigNew = { ...materialsNameConfig };
            ConfigNew.sName = `sMaterialsName${item}`;
            ConfigNew.sAssignField = ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);

            ConfigNew = { ...printModePoConfig };
            ConfigNew.sName = `iPrintModePo${item}`;
            ConfigNew.sAssignField = ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);

            ConfigNew = { ...positiveColorConfig };
            ConfigNew.sName = `iPositiveColor${item}`;
            ConfigNew.sAssignField = ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);
            if (sBackProcessClassifyData !== '') {
              sBackProcessClassifyData.filter(processClassify => processClassify.sType !== '3').forEach((processClassify) => {
                ConfigNew = { ...processNameConfig };
                ConfigNew.sName = processClassify.sId + item;
                masterConfig.gdsconfigformslave.push(ConfigNew);
              });
            }
          });
          if (sBackProcessClassifyData !== '') {
            sBackProcessClassifyData.filter(processClassify => processClassify.sType === '3').forEach((processClassify) => {
              ConfigNew = { ...processNameConfig };
              ConfigNew.sName = processClassify.sId;
              masterConfig.gdsconfigformslave.push(ConfigNew);
            });
          }
        }
        const returnChange = this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, true);
        this.props.onSaveState({ ...returnChange, sBackProcessClassifyData, masterConfig });
      } else { /*   失败   */
        message.error(dataReturn.msg);
      }
    } else {
      this.props.onChange(name, sFieldName, changeValue, sId, dropDownData);
    }
  };

  /* 数据生成按钮 */
  handleDataCreate= async () => {
    let { checkProcessClassifyData } = this.props;
    const {
      masterData, slaveConfig, materialsConfig, processConfig,
    } = this.props;
    const { token } = this.props.app;
    const paramMap = {};
    const { sAllPartsName } = masterData;
    let allPartsName = [];
    if (sAllPartsName !== undefined) {
      allPartsName = sAllPartsName.split(',');
    }
    let cpProcessName = '';
    checkProcessClassifyData = commonUtils.isEmptyArr(checkProcessClassifyData) ? [] : checkProcessClassifyData;
    // paramMap.modelName = masterData.modelName;
    paramMap.sProductClassifyId = masterData.sProductClassifyId;
    paramMap.sProductId = masterData.sProductId;
    paramMap.sProductStyleId = masterData.sProductStyleId;
    paramMap.sProductStyle = masterData.sProductStyle;
    paramMap.dProductWidth = masterData.sProductStyle.split('*').length > 0 ? masterData.sProductStyle.split('*')[1] : 0;
    paramMap.dProductLength = masterData.sProductStyle.split('*').length > 0 ? masterData.sProductStyle.split('*')[0] : 0;
    paramMap.dProductHeight = 0;
    paramMap.dProductQty = masterData.dProductQty;
    const partsInfo = [];
    allPartsName.forEach((item) => {
      const partInfo = {};
      partInfo.sPartsName = item;
      partInfo.dPartsQty = masterData.dProductQty;
      partInfo.dSumPQty = masterData[`dSumPQty${item}`];
      const materialsInfo = [];
      const material = {};
      material.sMaterialsId = masterData[`sMaterialsId${item}`];
      material.sMaterialsNo = masterData[`sMaterialsNo${item}`];
      material.sMaterialsName = masterData[`sMaterialsName${item}`] !== undefined && masterData[`sMaterialsName${item}`].split('[-]').length > 1 ? masterData[`sMaterialsName${item}`].split('[-]')[1] : masterData[`sMaterialsName${item}`];
      materialsInfo.push(material);
      partInfo.materialsInfo = materialsInfo;
      partInfo.iPositiveColor = masterData[`iPositiveColor${item}`];
      partInfo.iPrintModePo = masterData[`iPrintModePo${item}`];
      if (material.sMaterialsId !== undefined && material.sMaterialsId !== '') {
        const processInfo = [];
        checkProcessClassifyData.filter(card => card.sPartsName === item && card.sType !== '3').forEach((card) => {
          const process = {};
          process.sProductClassifyId = card.sId;
          process.sProcessId = masterData[card.sId + item];
          if (masterData[card.sId + card.sName + item] !== undefined) {
            process.sProcessName = masterData[card.sId + card.sName + item];
            process.sType = masterData[card.sId + card.sType + item];
            processInfo.push(process);
          }
        });
        partInfo.processInfo = processInfo;
        partsInfo.push(partInfo);
      }
    });
    const productProcess = [];
    checkProcessClassifyData.filter(card => card.sType === '3').forEach((card) => {
      const process = {};
      process.sProductClassifyId = card.sId;
      process.sProcessId = masterData[card.sId];
      process.sProcessName = masterData[card.sId + card.sName];
      if (masterData[card.sId + card.sName] !== undefined) {
        cpProcessName = cpProcessName === '' ? masterData[card.sId + card.sName] : `${cpProcessName},${masterData[card.sId + card.sName]}`;
        productProcess.push(process);
      }
    });
    paramMap.cpProcessName = cpProcessName;
    paramMap.productProcessInfo = productProcess;
    paramMap.partsInfo = partsInfo;
    const url = `${commonConfig.server_host}calculationStd/countMoney`;
    const dataReturn = (await commonServices.postValueService(token, paramMap, url)).data;
    if (dataReturn.code === 1) {
      const { partsNewInfo, productProcessInfo } = dataReturn.dataset.rows[0];
      const slaveData = [];
      const controlData = [];
      const materialsData = [];
      const processData = [];
      const tableDataRow = {};
      for (const item of slaveConfig.gdsconfigformslave) {
        tableDataRow[item.sName] = masterData[item.sName];
      }
      tableDataRow.sId = commonUtils.createSid();
      tableDataRow.handleType = 'add';
      tableDataRow.iOrder = 1;
      tableDataRow.sParentId = masterData.sId;
      slaveData.push(tableDataRow);
      partsNewInfo.forEach((partInfo, iIndex) => {
        const partsDataRow = {};
        for (const child of Object.keys(partInfo)) {
          partsDataRow[child] = partInfo[child];
        }
        partsDataRow.handleType = 'add';
        partsDataRow.iOrder = iIndex;
        partsDataRow.sId = commonUtils.createSid();
        partsDataRow.sParentId = masterData.sId;
        controlData.push(partsDataRow);
        // 材料信息
        partInfo.materialsInfo.forEach((materialInfo, iOrder) => {
          const materialDataRow = {};
          for (const item of materialsConfig.gdsconfigformslave) {
            materialDataRow[item.sName] = materialInfo[item.sName];
          }
          materialDataRow.handleType = 'add';
          materialDataRow.sType = '0';
          materialDataRow.iPartOrder = iIndex;
          materialDataRow.iOrder = iOrder;
          materialDataRow.sPartsName = partsDataRow.sPartsName;
          materialDataRow.sId = commonUtils.createSid();
          materialDataRow.sParentId = masterData.sId;
          materialDataRow.sControlId = partsDataRow.sId;
          materialsData.push(materialDataRow);
        });
        // 工序信息
        const processPrintDataRow = {};
        processPrintDataRow.handleType = 'add';
        processPrintDataRow.sProcessId = partInfo.sProcessId;
        processPrintDataRow.sType = partInfo.sType;
        processPrintDataRow.iPartOrder = iIndex;
        processPrintDataRow.iOrder = 1;
        processPrintDataRow.sProcessName = partInfo.sProcessName;
        processPrintDataRow.sPartsName = partsDataRow.sPartsName;
        processPrintDataRow.dProcessInQty = partInfo.dProcessInQty;
        processPrintDataRow.dLossQty = partInfo.dLossQty;
        processPrintDataRow.dProcessOutQty = partInfo.dProcessOutQty;
        processPrintDataRow.sId = commonUtils.createSid();
        processPrintDataRow.sParentId = masterData.sId;
        processPrintDataRow.sControlId = partsDataRow.sId;
        processData.push(processPrintDataRow);

        partInfo.processInfo.forEach((process, iOrder) => {
          const processAfterDataRow = {};
          for (const item of processConfig.gdsconfigformslave) {
            processAfterDataRow[item.sName] = process[item.sName];
          }
          for (const child of Object.keys(process)) {
            processAfterDataRow[child] = process[child];
          }
          processAfterDataRow.handleType = 'add';
          processAfterDataRow.sProcessId = process.sProcessId;
          processAfterDataRow.sType = process.sType;
          processAfterDataRow.iPartOrder = iIndex;
          processAfterDataRow.iOrder = iOrder;
          processAfterDataRow.sPartsName = partsDataRow.sPartsName;
          processAfterDataRow.sId = commonUtils.createSid();
          processAfterDataRow.sParentId = masterData.sId;
          processAfterDataRow.sControlId = partsDataRow.sId;
          processData.push(processAfterDataRow);
        });
      });
      productProcessInfo.forEach((process, iOrder) => {
        const processProductDataRow = {};
        for (const item of processConfig.gdsconfigformslave) {
          processProductDataRow[item.sName] = process[item.sName];
        }
        for (const child of Object.keys(process)) {
          processProductDataRow[child] = process[child];
        }
        processProductDataRow.handleType = 'add';
        processProductDataRow.sType = '3';
        processProductDataRow.sPartsName = '';
        processProductDataRow.iPartOrder = 999;
        processProductDataRow.iOrder = iOrder;
        processProductDataRow.sId = commonUtils.createSid();
        processProductDataRow.sParentId = masterData.sId;
        processData.push(processProductDataRow);
      });
      processData.sort((g1, g2) => {
        let sPartOrder1 = `0000${g1.iPartOrder}`;
        sPartOrder1 = sPartOrder1.substring(sPartOrder1.length - 3);
        let sOrder1 = `000${g1.iOrder}`;
        sOrder1 = sOrder1.substring(sOrder1.length - 3);

        let sPartOrder2 = `0000${g2.iPartOrder}`;
        sPartOrder2 = sPartOrder2.substring(sPartOrder2.length - 3);
        let sOrder2 = `000${g2.iOrder}`;
        sOrder2 = sOrder2.substring(sOrder2.length - 3);
        return parseInt(sPartOrder1 + g1.sType + sOrder1, 10) - parseInt(sPartOrder2 + g2.sType + sOrder2, 10);
      });
      this.props.onSaveState({
        slaveData, controlData, materialsData, processData,
      });
    }
  }

  /* 勾选工序分类 */
  handleProcessChange=(e, value, sPartsName) => {
    let { checkProcessClassifyData } = this.props;
    let index = -1;
    if (commonUtils.isNotEmptyArr(checkProcessClassifyData)) {
      index = checkProcessClassifyData.findIndex(item => (item.sId === value.sId && item.sPartsName === sPartsName));
    } else {
      checkProcessClassifyData = [];
    }
    if (e.target.checked) {
      if (index <= -1) {
        const newvalue = { ...value };
        newvalue.sPartsName = sPartsName;
        checkProcessClassifyData.push(newvalue);
      }
    } else if (index > -1) {
      checkProcessClassifyData.splice(index, 1);
    }
    this.props.onSaveState({ checkProcessClassifyData });
  };

  handleSelectChangeProcess = (sAssignField, value, option) => {
    const { masterData } = this.props;
    if (sAssignField !== undefined) {
      // 这一段是处理工序的赋值字段，原因工序是动态生成，没用showtype
      const sAssignFields = sAssignField.split(',');
      const recordRow = option.props['data-recordrow'];
      sAssignFields.forEach((item) => {
        const itemsplits = item.split(':');
        masterData[`${itemsplits[0]}`] = recordRow[itemsplits[1]];
      });
      this.props.onSaveState({ masterData });
    }
  }

  handleA = (sId) => {
    const { sBackProcessData } = this.props;
    const data = sBackProcessData.filter(item => item.sParentId === sId);
    const optionProcess = [];
    data.forEach((item) => {
      optionProcess.push(<Option key={item.sId} value={item.sId} data-recordrow={item}>{item.sProcessName}</Option>);
    });
    return optionProcess;
  }

  handleSave = async () => {
    this.form.validateFieldsAndScroll((err) => {
      /*   验证通过与不通过走不同的流程   */
      if (err) { /*   验证失败   */
        /*   直接渲染显示错误提示   */
        for (const key of Object.keys(err)) {
          message.warning(err[key].errors[0].message);
        }
      } else { /*   验证成功   */
        const {
          masterConfig, masterData, slaveConfig, slaveData, slaveDelData, controlConfig, controlData, controlDelData,
          materialsConfig, materialsData, materialsDelData, processConfig, processData, processDelData,
        } = this.props;

        if (!commonBusiness.validateTable(slaveConfig, slaveData) || !commonBusiness.validateTable(controlConfig, controlData) ||
        (!commonBusiness.validateTable(materialsConfig, materialsData)) || !commonBusiness.validateTable(processConfig, processData)) {
          return;
        }

        const data = [];
        data.push(commonBusiness.mergeData('master', masterConfig.sTbName, [masterData]));
        data.push(commonBusiness.mergeData('slave', slaveConfig.sTbName, slaveData, slaveDelData));
        data.push(commonBusiness.mergeData('control', controlConfig.sTbName, controlData, controlDelData));
        data.push(commonBusiness.mergeData('materials', materialsConfig.sTbName, materialsData, materialsDelData));
        data.push(commonBusiness.mergeData('process', processConfig.sTbName, processData, processDelData));
        this.props.onSaveData({ data, sClientType: '1' });
      }
    });
  };

  /** 控制选择控制表时，显示部件工序与成品工序 */
  handleFilterData = (name, dataIndex, value, record) => {
    return (commonUtils.isNotEmptyStr(record.sType) && record.sType === '3') ||
      (commonUtils.isNotEmptyStr(record.sControlId) && record.sControlId.toString().toLowerCase().includes(value.toLowerCase()));
  };

  /**   添加表格空行   */
  handleTableAdd = (name) => {
    /*   外置处理业务   */
    const {
      gdsformconst, controlData, controlSelectedRowKeys, [`${name}Data`]: tableData,
    } = this.props;
    if (name === 'materials' || name === 'process') {
      const tableDataRow = this.props.onDataRowAdd(name, true);
      if (commonUtils.isEmptyArr(controlSelectedRowKeys)) {
        message.warn(commonFunc.showMessage(gdsformconst, 'pleaseChooseParts')); // 请选择部件
        return;
      }
      const iIndex = controlData.findIndex(item => item.sId === controlSelectedRowKeys[0]);
      if (iIndex > -1) {
        if (commonUtils.isEmpty(controlData[iIndex].sPartsName) === '') {
          message.warn(commonFunc.showMessage(gdsformconst, 'partsNameNotNull')); // 部件名称不能为空
          return;
        }
        tableDataRow.sControlId = controlData[iIndex].sId;
        tableDataRow.sPartsName = controlData[iIndex].sPartsName;
      }
      tableData.push(tableDataRow);
      this.props.onSaveState({ [`${name}Data`]: tableData });
    } else {
      this.props.onDataRowAdd(name);
    }
  };
  /**   删除表格数据   */
  otherTableDel = (name, tableSelectedRowKeys) => {
    const tableData = this.props[`${name}Data`];
    let tableDelData = this.props[`${name}DelData`];
    tableDelData = commonUtils.isEmptyArr(tableDelData) ? [] : tableDelData;
    for (const sId of tableSelectedRowKeys) {
      /*   看看删除集合和从表中是否都存在该条数据   */
      let tableDataIndex = tableData.findIndex(item => item.sControlId === sId);
      while (tableDataIndex > -1) {
        /*   删除从表中的数据并存入删除集合中   */
        const slaveDataFilter = tableData[tableDataIndex];
        tableData.splice(tableDataIndex, 1);
        slaveDataFilter.handleType = 'del';
        tableDelData.push(slaveDataFilter);
        tableDataIndex = tableData.findIndex(item => item.sControlId === sId);
      }
    }
    return { [`${name}Data`]: tableData, [`${name}DelData`]: tableDelData, [`${name}SelectedRowKeys`]: [] };
  }
  /**   删除表格数据   */
  handleTableDel = (name) => {
    if (name === 'control') {
      const tableSelectedRowKeys = this.props[`${name}SelectedRowKeys`];
      if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) {
        const materialsReturnData = this.otherTableDel('materials', tableSelectedRowKeys);
        const processReturnData = this.otherTableDel('process', tableSelectedRowKeys);
        const controlReturnData = this.props.onDataRowDel(name, true);
        this.props.onSaveState({
          ...materialsReturnData,
          ...processReturnData,
          ...controlReturnData,
        });
        return true;
      } else {
        return false;
      }
    } else {
      return this.props.onDataRowDel(name);
    }
  };

  handleCalculation = async () => {
    const dataUrl = `${commonConfig.server_host}business/addWorksheet?sModelsId=${this.props.sModelsId}`;
    const {
      masterConfig, masterData, slaveConfig, controlConfig, materialsConfig, processConfig, app,
    } = this.props;
    let {
      slaveData, controlData, materialsData, processData,
    } = this.props;
    const data = [];
    // data.push(commonBusiness.mergeData(`${masterConfig.sTbName}_Tmp`, [masterData], [], true));
    data.push(commonBusiness.mergeData('slave', `${slaveConfig.sTbName.toLowerCase()}_tmp`, slaveData, [], true));
    data.push(commonBusiness.mergeData('control', `${controlConfig.sTbName.toLowerCase()}_tmp`, controlData, [], true));
    data.push(commonBusiness.mergeData('materials', `${materialsConfig.sTbName.toLowerCase()}_tmp`, materialsData, [], true));
    data.push(commonBusiness.mergeData('process', `${processConfig.sTbName.toLowerCase()}_tmp`, processData, [], true));
    const value = { data, sClientType: '1', sGuid: masterData.sId };
    const dataReturn = (await commonServices.postValueService(this.props.app.token, value, dataUrl)).data;
    if (dataReturn.code === 1) { /*   成功   */
      const valueReturn = dataReturn.dataset.rows[0];
      slaveData = valueReturn[`${slaveConfig.sTbName.toLowerCase()}_tmp`];
      controlData = valueReturn[`${controlConfig.sTbName.toLowerCase()}_tmp`];
      materialsData = valueReturn[`${materialsConfig.sTbName.toLowerCase()}_tmp`];
      processData = valueReturn[`${processConfig.sTbName.toLowerCase()}_tmp`];
      this.props.onSaveState({
        slaveData, controlData, materialsData, processData,
      });

      message.success(commonFunc.getConfigShowName(masterConfig, 'BtnCalculation') + commonFunc.showMessage(app.commonConst, 'handleSuccess'));
    } else { /*   失败   */
      message.error(dataReturn.msg);
    }
  }
  /** 按钮操作事件 */
  handleButtonClick = (name) => {
    if (name === 'BtnCalculation') {
      this.handleCalculation();
    }
  }

  /*  上一条、下一条、首条、末条 */
  handleSearchData = async (handleType) => {
    const {
      controlConfig, materialsConfig, processConfig,
    } = this.props;
    const bReturn = await this.props.onSearchData(handleType);
    if (bReturn) {
      this.handleGetData(controlConfig, materialsConfig, processConfig);
    }
  };

  /**   点击修改按钮操作   */
  handleEdit = () => {
    this.props.onEdit();
    const { controlConfig, materialsConfig, processConfig } = this.props;
    this.handleGetData(controlConfig, materialsConfig, processConfig);
  };

  /*   单据页复制到   */
  handleCopyTo = (name, sActiveId) => {
    /*   待用数据声明   */
    const {
      dispatch, masterConfig, masterData, slaveData, controlData, materialsData, processData,
    } = this.props;
    const copyTo = {};
    const copyToConfig = masterConfig.gdsconfigformslave.filter(item => item.sControlName.includes(name));
    copyTo.name = name;
    copyTo.config = copyToConfig;
    copyTo.masterData = masterData;
    copyTo.slaveData = slaveData;
    copyTo.controlData = controlData;
    copyTo.materialsData = materialsData;
    copyTo.processData = processData;
    dispatch({
      type: 'content/onRouter',
      payload: {
        url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
        copyTo,
      },
    });
  };

  /* 确定要删除 */
  handleOkDel = async (props) => {
    /*   数据参数   */
    const {
      token, sModelsId, masterConfig, masterData, slaveConfig, checkConfig, controlConfig, materialsConfig, processConfig,
    } = props;
    const value = {
      sClientType: '1',
      data: {
        sMasterTable: masterConfig.sTbName,
        sId: [masterData.sId],
        sSlaveTable: [
          {
            tableName: slaveConfig.sTbName,
            relationName: 'sParentId',
          }, {
            tableName: checkConfig.sTbName,
            relationName: 'sBillId',
          }, {
            tableName: controlConfig.sTbName,
            relationName: 'sParentId',
          }, {
            tableName: materialsConfig.sTbName,
            relationName: 'sParentId',
          }, {
            tableName: processConfig.sTbName,
            relationName: 'sParentId',
          }],
      },
    };
    const url = `${commonConfig.server_host}business/delMasSlaBusinessData?sModelsId=${sModelsId}`;
    /*   接收返回值   */
    const { data } = await commonServices.postValueService(token, value, url);
    if (data.code === 1) {
      /*   数据删除成功   */
      if (this.props.app.currentPane.refresh !== undefined) {
        this.props.app.currentPane.refresh();
      }
      this.handleDelDataSuccess(props);
    } else { /*   失败   */
      this.props.getServiceError(data);
    }
  };

  /* 删除 */
  handleDel = (obj) => {
    const props = { ...this.props, ...this.state };
    const onOkDel = this.handleOkDel;
    confirm({
      title: obj.title,
      onOk() {
        onOkDel(props);
      },
      onCancel() {
      },
    });
  };

  /*   取消操作  */
  handleCancel = (obj) => {
    /*   待用数据声明   */
    const {
      masterConfig, slaveConfig, checkConfig, controlConfig, materialsConfig, processConfig,
    } = this.props;
    const onGetData = this.props.onGetData;
    const onGetDataOk = this.handleGetData;
    const onSaveStateOk = this.props.onSaveState;
    confirm({
      title: obj.title,
      onOk() {
        onGetData(masterConfig, slaveConfig, checkConfig);
        onGetDataOk(controlConfig, materialsConfig, processConfig);
        onSaveStateOk({ enabled: false });
      },
      onCancel() {
      },
    });
  };

  /**  点击新增按钮   */
  handleAdd = (config, copyTo) => {
    let configNew = {};
    if (commonUtils.isEmptyObject(config)) {
      const { masterConfig, slaveConfig } = this.props;
      configNew.masterConfig = masterConfig;
      configNew.slaveConfig = slaveConfig;
    } else {
      configNew = config;
    }
    const state = this.props.onAdd(configNew, copyTo, true);
    const { masterData, slaveData } = state;
    const controlData = [];
    const materialsData = [];
    const processData = [];
    if (commonUtils.isNotEmptyObject(copyTo)) {
      const copyToControlConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.control`.toLowerCase());
      const copyToMaterialsConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.materials`.toLowerCase());
      const copyToProcessConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.process`.toLowerCase());
      const controlAssignField = commonUtils.isNotEmptyArr(copyToControlConfig) ? copyToControlConfig[0].sAssignField : '';
      const materialsAssignField = commonUtils.isNotEmptyArr(copyToMaterialsConfig) ? copyToControlConfig[0].sAssignField : '';
      const processAssignField = commonUtils.isNotEmptyArr(copyToProcessConfig) ? copyToControlConfig[0].sAssignField : '';

      const newCopyTo = {};
      newCopyTo.masterData = copyTo.masterData;
      newCopyTo.slaveData = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];
      copyTo.controlData.forEach((controlItem) => {
        newCopyTo.controlData = controlItem;
        let controlRow = commonFunc.getDefaultData(config.controlConfig, newCopyTo); // 取默认值
        controlRow = { ...controlRow, ...commonFunc.getAssignFieldValue(controlAssignField, controlItem, newCopyTo) }; // 取赋值字段
        controlRow.handleType = 'add';
        controlRow.sId = commonUtils.createSid();
        controlRow.sParentId = masterData.sId;
        controlData.push(controlRow);

        copyTo.materialsData.filter(item => item.sControlId === controlItem.sId).forEach((materialsItem) => {
          newCopyTo.materialsData = materialsItem;
          let materialsRow = commonFunc.getDefaultData(config.materialsConfig, newCopyTo); // 取默认值
          materialsRow = { ...materialsRow, ...commonFunc.getAssignFieldValue(materialsAssignField, materialsItem, newCopyTo) }; // 取赋值字段
          materialsRow.handleType = 'add';
          materialsRow.sId = commonUtils.createSid();
          materialsRow.sParentId = masterData.sId;
          materialsRow.sControlId = controlRow.sId;
          materialsData.push(materialsRow);
        });

        copyTo.processData.filter(item => item.sControlId === controlItem.sId).forEach((processItem) => {
          newCopyTo.processData = processItem;
          let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
          processRow = { ...processRow, ...commonFunc.getAssignFieldValue(processAssignField, processItem, newCopyTo) }; // 取赋值字段
          processRow.handleType = 'add';
          processRow.sId = commonUtils.createSid();
          processRow.sParentId = masterData.sId;
          processRow.sControlId = controlRow.sId;
          processData.push(processRow);
        });
      });

      copyTo.materialsData.filter(item => item.sType === '2').forEach((materialsItem) => {
        newCopyTo.materialsData = materialsItem;
        let materialsRow = commonFunc.getDefaultData(config.materialsConfig, newCopyTo); // 取默认值
        materialsRow = { ...materialsRow, ...commonFunc.getAssignFieldValue(materialsAssignField, materialsItem, newCopyTo) }; // 取赋值字段
        materialsRow.handleType = 'add';
        materialsRow.sId = commonUtils.createSid();
        materialsRow.sParentId = masterData.sId;
        materialsData.push(materialsRow);
      });

      copyTo.processData.filter(item => item.sType === '3').forEach((processItem) => {
        newCopyTo.processData = processItem;
        let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
        processRow = { ...processRow, ...commonFunc.getAssignFieldValue(processAssignField, processItem, newCopyTo) }; // 取赋值字段
        processRow.handleType = 'add';
        processRow.sId = commonUtils.createSid();
        processRow.sParentId = masterData.sId;
        processData.push(processRow);
      });
    }
    const stateNew = {
      ...state,
      controlData,
      controlSelectedRowKeys: [],
      materialsData,
      materialsSelectedRowKeys: [],
      processData,
      processSelectedRowKeys: [],
    };
    this.props.onSaveState(stateNew);
  };


  render() {
    const { pageLoading, masterData } = this.props;
    const imgSrc = commonBusiness.handleAddIcon(masterData);
    return (
      <Spin spinning={pageLoading}>
        <WorkOrderComponent
          {...this.props}
          {...this.state}
          onReturnForm={this.handleForm}
          onSubmit={this.handleSave}
          onMasterChange={this.handleMasterChange}
          handleDataCreate={this.handleDataCreate}
          handleProcessChange={this.handleProcessChange}
          handleSelectChangeProcess={this.handleSelectChangeProcess}
          handleA={this.handleA}
          onEdit={this.handleEdit}
          onCopyTo={this.handleCopyTo}
          onAdd={this.handleAdd}
          onDel={this.handleDel}
          onCancel={this.handleCancel}
          onFilterData={this.handleFilterData}
          onDataRowAdd={this.handleTableAdd}
          onDataRowDel={this.handleTableDel}
          getMenuStatus={this.getMenuStatus}
          onButtonClick={this.handleButtonClick}
          onNext={this.handleSearchData.bind(this, 'next')}
          onBtnPrior={this.handleSearchData.bind(this, 'up')}
          onBtnFirst={this.handleSearchData.bind(this, 'first')}
          onBtnLast={this.handleSearchData.bind(this, 'end')}
          imgSrc={imgSrc}
        />
      </Spin>
    );
  }
}

const WorkOrderComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const {
    form, onReturnForm, slaveData, slavePagination,
  } = props;
  /*   回带表单   */
  onReturnForm(form);
  const propsType = {
    ...props,
    onChange: props.onMasterChange,
  };
  const pagination = {
    total: commonUtils.isEmptyArr(slaveData) ? 0 : slaveData.length,
    current: commonUtils.isEmptyObject(slavePagination) ? 1 : slavePagination.current,
    size: 'large',
    pageSize: commonConfig.pageSize,
    showQuickJumper: true,
  };
  const slaveTableProps = {
    ...commonBusiness.getTableTypes('slave', props),
    tableProps: { pagination, onChange: props.onTitleChange },
  };
  const materialsPropsType = {
    ...commonBusiness.getTableTypes('materials', props),
    filteredValue: props.controlSelectedRowKeys,
    onFilterData: props.onFilterData,
  };
  const processPropsType = {
    ...commonBusiness.getTableTypes('process', props),
    filteredValue: props.controlSelectedRowKeys,
    onFilterData: props.onFilterData,
  };
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar {...props} />
        </Header>
        <Layout className={styles.clayout}>
          <Content className={styles.content}>
            <CommonView {...propsType} />
            <SplitPaste {...props} />
            <div id="slaveTabs" className={styles.bShow}>
              <div>
                <Avatar src={props.imgSrc} />
              </div>
              <Tabs className={styles.slaveTabs}>
                <TabPane tab="主体内容" key={2}>
                  <StaticEditTable {...slaveTableProps} />
                </TabPane>
                <TabPane tab="审批信息" key={3}>
                  <StaticEditTable {...commonBusiness.getTableTypes('check', props)} />
                </TabPane>
              </Tabs>
            </div>
            <StaticEditTable {...commonBusiness.getTableTypes('control', props)} />
            <StaticEditTable {...materialsPropsType} />
            <StaticEditTable {...processPropsType} />
          </Content>
        </Layout>
      </Layout>
    </Form>
  );
});

export default CommonBase(CommonSales(WorkOrder));
